package com.zp.kidshop.common.filter;

import java.io.IOException;
import java.util.LinkedList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zp.kidshop.common.exception.BaseUnException;
import com.zp.kidshop.common.pojo.SysProp;
import com.zp.kidshop.common.util.LogUtil;


public class KidShopFilter implements Filter{

	//加载
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("\n\n\n\n\n启动加载中...........................\n\n\n\n\n");
		
	}

	//过滤
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest  httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		LogUtil.setLogList(new LinkedList<String>());                        // 传入当前线程LogList
		try {
			LogUtil.addLog("[请求IP]：" + httpServletRequest.getRemoteAddr());
			String rooturl = httpServletRequest.getContextPath();
			request.setAttribute("rooturl", rooturl);
			
			//域名
//			StringBuffer url = httpServletRequest.getRequestURL();  
//			String tempContextUrl = url.delete(url.length() - httpServletRequest.getRequestURI().length(), url.length()).append("/").toString(); 
			//域名+项目名
			StringBuffer url = httpServletRequest.getRequestURL();  
			String tempContextUrl = url.delete(url.length() - httpServletRequest.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString(); 
			
			request.setAttribute("rooturl1", tempContextUrl);
			
			chain.doFilter(request, response);
			
			LogUtil.print(LogUtil.WARN, null);
		} catch (SecurityException e) {
			e.printStackTrace();
			throw new BaseUnException(SysProp.ERR_NO_SECURITYC, SysProp.ERR_NO_SECURITYM, e);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new BaseUnException(SysProp.ERR_INVOCATION_TARGETC, SysProp.ERR_ILLEGAL_ARGUMENTM, e);
		}
	}

	//销毁
	public void destroy() {
		System.out.println("\n\n\n\n\n销毁中...........................\n\n\n\n\n");
	}

}
